package com.haha.qqchannelbot.service;

import com.haha.qqchannelbot.entity.LiangEnum;
import com.haha.qqchannelbot.entity.fortune.AnimalEnum;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Log4j2
public class FortuneService {

    @Resource
    private RestTemplate restTemplate;

    FortuneService() {
        log.info("FortuneService init");
    }


    /**
     * 生肖运势
     * @param name
     * @return
     */
    public String animalFortune(String name) {
        if (!isChinese(name)) {
            return "生肖运势：请输入正确的生肖名称";
        }
        if (name.length() > 2) {
            return "生肖运势：请输入正确的生肖";
        }

        AnimalEnum animalEnum = AnimalEnum.getAnimalEnum(name);
        if (null == animalEnum) {
            return "生肖运势：请输入正确的生肖";
        }

        String url = animalEnum.getUrl();
        StringBuilder result = new StringBuilder();
        result.append(animalEnum.getEmoji()).append("\n");

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36");
        httpHeaders.add("Referer", "https://www.k366.com/");
        httpHeaders.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");

        HttpEntity httpEntity = new HttpEntity(httpHeaders);

        ResponseEntity<String> exchange = restTemplate.exchange(String.format(url), HttpMethod.POST, httpEntity, String.class);
//        System.out.println(exchange.getBody());

        Document document = Jsoup.parse(exchange.getBody());
        document.getElementsByClass("sxxiangqing").forEach(element -> {
            element.getElementsByClass("xiang_box").forEach(element1 -> {
                String tit = element1.getElementsByClass("xiang_box_tit").get(0).text();
                result.append(tit).append("\n");

                Element cfYs = element1.getElementsByClass("cf_ys").get(0);
                String cfYsText = cfYs.getElementsByTag("span").get(0).text();
                String liang = cfYs.getElementsByTag("i").get(0).className();
                result.append(cfYsText).append(LiangEnum.getStar(liang)).append("\n");

                String xDetails = element1.getElementsByClass("x_details").get(0).text();
                result.append(xDetails).append("\n");

            });
        });

        document.getElementsByClass("kaiyun_item").forEach(element -> {
            String text = element.text();
            if (text.contains("生肖贵人")) {
                AnimalEnum animalEnum2 = AnimalEnum.getAnimalEnum(text.substring(4).trim());
                text = text + " " + animalEnum2.getEmoji();
            }
            result.append(text).append("\n");
        });

        result.append("⭐此结果仅供娱乐参考，切勿当真⭐").append("\n");

        return result.toString();
    }

    /**
     * 姓名打分
     * @param name
     * @return
     */
    public String nameFortune(String name) {

        if (!isChinese(name)) {
            return "姓名打分：请输入中文名字";
        }

        try {
            boolean b = BaiduContentReviewService.checkContent(name);
            if (b) {
                return "姓名打分：请输入合法的名字";
            }
        } catch (IOException e) {
            log.error("校验失败", e);
        }

        String url = "https://cm.k366.com?xingming=%s&frontType=1";
        StringBuilder result = new StringBuilder();
        result.append("⭐⭐⭐").append("\n");
        result.append("姓名打分：").append(name).append("\n");
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36");
        httpHeaders.add("Referer", "https://cm.k366.com/");
        httpHeaders.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");

        HttpEntity httpEntity = new HttpEntity(httpHeaders);

        ResponseEntity<String> exchange = restTemplate.exchange(String.format(url, name), HttpMethod.POST, httpEntity, String.class);

        String body = exchange.getBody();
//        System.out.println(body);

        Document document = Jsoup.parse(body);

        Elements elementsByClass = document.getElementsByClass("box-result");
        elementsByClass.get(1).getElementsByTag("p").forEach(element -> {
//            System.out.println(element.text());
            result.append(element.text()).append("\n");
        });
        result.append("⭐此结果仅供娱乐参考，切勿当真⭐").append("\n");
        result.append("⭐⭐⭐").append("\n");
        return result.toString();
    }

    /**
     * 是否是中文
     * @param str
     * @return
     */
    public boolean isChinese(String str) {
        Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5]+$");
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }



}
